package resourceModule.component;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IAuthorityResourceInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnAuthorityManager;

public class QueryResourceByRole extends DefaultComponent {
	private static final String QUERY_SQL = "select * from SATURN_AUTHORITY_ROLE_RES where ROLE_ID = ?";

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		String roleSerialNo = (String) parameterContext.getParameterValue(0);

		List<IAuthorityResourceInfo> allResourceList = SaturnAuthorityManager
				.getInstance().getAllResources();


		List<IAuthorityResourceInfo> resourceListWithRole = new ArrayList<IAuthorityResourceInfo>();
		List<IAuthorityResourceInfo> resourceListWithoutRole = new ArrayList<IAuthorityResourceInfo>();
		List<String> resourceNoList = new ArrayList<String>();
		PreparedStatement st = null;
		ResultSet rs = null;

		try {
			st = parameterContext.getConnection().prepareStatement(QUERY_SQL);
			st.setString(1, roleSerialNo);

			
		
			rs = st.executeQuery();
			
			while (rs.next()) {
				String resourceNo = rs.getString("RESOURCE_ID");
				resourceNoList.add(resourceNo);
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		if (resourceNoList.size() > 0) {
			for (IAuthorityResourceInfo resourceInfo : allResourceList) {
				for (String resourceNo : resourceNoList) {
					
					if (resourceNo.equals(resourceInfo.getResourceKey())) {
						resourceListWithRole.add(resourceInfo);
					}
				}
			}
		}
		for (IAuthorityResourceInfo resourceInfo : allResourceList) {
			if (!resourceListWithRole.contains(resourceInfo)) {
				resourceListWithoutRole.add(resourceInfo);
			}
		}
		parameterContext.setParameter(1, resourceListWithRole);
		parameterContext.setParameter(2, resourceListWithoutRole);
	}
}